<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="短剧标题" prop="title">
              <el-input v-model="queryParams.title" placeholder="请输入短剧标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="副标题" prop="subTitle">
              <el-input v-model="queryParams.subTitle" placeholder="请输入副标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="简介" prop="description">
              <el-input v-model="queryParams.description" placeholder="请输入简介" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['content:dramas:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['content:dramas:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['content:dramas:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['content:dramas:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="dramasList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="短剧ID" align="center" prop="dramaId" v-if="true" width="125" />
        <el-table-column label="短剧标题" align="center" prop="title" width="100"/>
        <el-table-column label="副标题" align="center" prop="subTitle" width="100"/>
        <el-table-column label="封面图" align="center" prop="cover" width="75">
          <template #default="scope">
            <el-image :src="scope.row.cover" fit="fill" :preview-src-list="[scope.row.cover]" width="50" height="50" />
          </template>
        </el-table-column>
        <!-- <el-table-column label="预告片URL" align="center" prop="trailerUrl" /> -->
        <el-table-column label="简介" align="center"  width="55" show-overflow-tooltip prop="description" />
        <!-- <el-table-column label="剧情介绍" align="center" prop="storyLine" /> -->
        <!-- <el-table-column label="发布日期" align="center" prop="releaseDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.releaseDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="完结" align="center" prop="isFinished" width="85">
          <template #default="scope">
                <el-tag type="primary" v-if="scope.row.isFinished === 0">连载中</el-tag>
                <el-tag type="success" v-else>已完结</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="VIP专享" align="center" prop="isVip" width="55">
          <template #default="scope">
             <el-icon v-if="scope.row.isVip === 1" style="color: #409eff;">
              <CircleCheck />
            </el-icon>
            <el-icon v-else style="color: #ff4949;">
              <CircleClose />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column label="新剧" align="center" prop="isNew" width="55">
          <template #default="scope">
            <el-icon v-if="scope.row.isNew === 1" style="color: #409eff;">
              <CircleCheck />
            </el-icon>
            <el-icon v-else style="color: #ff4949;">
              <CircleClose />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column label="热播" align="center" prop="isHot" width="55">
          <template #default="scope">
             <el-icon v-if="scope.row.isHot === 1" style="color: #409eff;">
              <CircleCheck />
            </el-icon>
            <el-icon v-else style="color: #ff4949;">
              <CircleClose />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column label="推荐" align="center" prop="isRecommended" width="55">
          <template #default="scope">
            <el-icon v-if="scope.row.isRecommended === 1" style="color: #409eff;">
              <CircleCheck />
            </el-icon>
            <el-icon v-else style="color: #ff4949;">
              <CircleClose />
            </el-icon>
          </template>
        </el-table-column>
        <!-- <el-table-column label="年龄分级：G/PG/PG-13/R" align="center" prop="ageRating" />
        <el-table-column label="播放次数" align="center" prop="playCount" />
        <el-table-column label="点赞数" align="center" prop="likeCount" />
        <el-table-column label="评论数" align="center" prop="commentCount" />
        <el-table-column label="分享数" align="center" prop="shareCount" />
        <el-table-column label="收藏数" align="center" prop="collectionCount" />
        <el-table-column label="追剧数" align="center" prop="followCount" />
        <el-table-column label="评分" align="center" prop="ratingScore" />
        <el-table-column label="评分人数" align="center" prop="ratingCount" /> -->
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template #default="scope">
            <el-tag type="primary" v-if="scope.row.status === 0">下架</el-tag>
            <el-tag type="success" v-else-if="scope.row.status === 1">上架</el-tag>
            <el-tag type="info" v-else>审核中</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center"  prop="auditStatus" width="85">
          <template #default="scope">
            <el-tag type="primary" v-if="scope.row.auditStatus === 0">待审核</el-tag>
            <el-tag type="success" v-else-if="scope.row.auditStatus === 1">通过</el-tag>
            <el-tag type="danger" v-else>拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核拒绝原因" align="center" prop="auditReason"  width="155" show-overflow-tooltip />
        <!-- <el-table-column label="排序顺序" align="center" prop="sortOrder" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="审核" placement="top" v-if="scope.row.auditStatus === 0">
              <el-button link type="primary" icon="Check" @click="handleCheck(scope.row)" v-hasPermi="['content:dramas:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['content:dramas:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['content:dramas:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 审核弹窗 -->
    <el-dialog :title="checkFormDialog.title" v-model="checkFormDialog.visible">
      <el-alert  v-loading="loadingAiStatus"
                 element-loading-background="rgba(0, 0, 0, 0.7)"
                 :title="checkForm.aiStatus" type="success" :closable="false" />
      <el-form ref="checkFormRef" :model="checkForm" label-width="80px">
        <el-form-item label="审核状态" prop="auditStatus">
          <el-radio-group v-model="checkForm.auditStatus">
            <el-radio label="1" :value="1">通过</el-radio>
            <el-radio label="2" :value="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="拒绝原因" prop="auditReason" v-if="checkForm.auditStatus === 2">
          <el-input v-model="checkForm.auditReason" placeholder="请输入审核拒绝原因" />
        </el-form-item>
      </el-form>
       <template #footer>
          <div class="dialog-footer">
            <el-button :loading="buttonLoading" type="primary" @click="submitCheckForm">确 定</el-button>
            <el-button @click="cancelCheckFormDialog">取 消</el-button>
          </div>
      </template>
    </el-dialog>

    <!-- 添加或修改短剧管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="dramasFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="短剧标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入短剧标题" />
        </el-form-item>
        <el-form-item label="副标题" prop="subTitle">
          <el-input v-model="form.subTitle" placeholder="请输入副标题" />
        </el-form-item>
        <el-form-item label="封面图URL" prop="cover">
          <el-input v-model="form.cover" placeholder="请输入封面图URL" />
        </el-form-item>
        <el-form-item label="海报图URL" prop="poster">
          <el-input v-model="form.poster" placeholder="请输入海报图URL" />
        </el-form-item>
        <el-form-item label="预告片URL" prop="trailerUrl">
          <el-input v-model="form.trailerUrl" placeholder="请输入预告片URL" />
        </el-form-item>
        <el-form-item label="简介" prop="description">
            <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="剧情介绍" prop="storyLine">
            <el-input v-model="form.storyLine" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="导演，多个用逗号分隔" prop="director">
          <el-input v-model="form.director" placeholder="请输入导演，多个用逗号分隔" />
        </el-form-item>
        <el-form-item label="编剧，多个用逗号分隔" prop="screenwriter">
          <el-input v-model="form.screenwriter" placeholder="请输入编剧，多个用逗号分隔" />
        </el-form-item>
        <el-form-item label="制作公司" prop="productionCompany">
          <el-input v-model="form.productionCompany" placeholder="请输入制作公司" />
        </el-form-item>
        <el-form-item label="发布日期" prop="releaseDate">
          <el-date-picker clearable
            v-model="form.releaseDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择发布日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="总集数" prop="totalEpisodes">
          <el-input v-model="form.totalEpisodes" placeholder="请输入总集数" />
        </el-form-item>
        <el-form-item label="当前集数" prop="currentEpisodes">
          <el-input v-model="form.currentEpisodes" placeholder="请输入当前集数" />
        </el-form-item>
        <el-form-item label="平均每集时长(秒)" prop="episodeDuration">
          <el-input v-model="form.episodeDuration" placeholder="请输入平均每集时长(秒)" />
        </el-form-item>
        <el-form-item label="总时长(秒)" prop="totalDuration">
          <el-input v-model="form.totalDuration" placeholder="请输入总时长(秒)" />
        </el-form-item>
        <el-form-item label="语言" prop="language">
          <el-input v-model="form.language" placeholder="请输入语言" />
        </el-form-item>
        <el-form-item label="地区" prop="region">
          <el-input v-model="form.region" placeholder="请输入地区" />
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-input v-model="form.year" placeholder="请输入年份" />
        </el-form-item>
        <el-form-item label="是否完结：0连载中，1已完结" prop="isFinished">
          <el-input v-model="form.isFinished" placeholder="请输入是否完结：0连载中，1已完结" />
        </el-form-item>
        <el-form-item label="是否VIP专享：0否，1是" prop="isVip">
          <el-input v-model="form.isVip" placeholder="请输入是否VIP专享：0否，1是" />
        </el-form-item>
        <el-form-item label="是否新剧：0否，1是" prop="isNew">
          <el-input v-model="form.isNew" placeholder="请输入是否新剧：0否，1是" />
        </el-form-item>
        <el-form-item label="是否热播：0否，1是" prop="isHot">
          <el-input v-model="form.isHot" placeholder="请输入是否热播：0否，1是" />
        </el-form-item>
        <el-form-item label="是否推荐：0否，1是" prop="isRecommended">
          <el-input v-model="form.isRecommended" placeholder="请输入是否推荐：0否，1是" />
        </el-form-item>
        <el-form-item label="画质：SD/HD/FHD/4K" prop="quality">
          <el-input v-model="form.quality" placeholder="请输入画质：SD/HD/FHD/4K" />
        </el-form-item>
        <el-form-item label="年龄分级：G/PG/PG-13/R" prop="ageRating">
          <el-input v-model="form.ageRating" placeholder="请输入年龄分级：G/PG/PG-13/R" />
        </el-form-item>
        <el-form-item label="播放次数" prop="playCount">
          <el-input v-model="form.playCount" placeholder="请输入播放次数" />
        </el-form-item>
        <el-form-item label="点赞数" prop="likeCount">
          <el-input v-model="form.likeCount" placeholder="请输入点赞数" />
        </el-form-item>
        <el-form-item label="评论数" prop="commentCount">
          <el-input v-model="form.commentCount" placeholder="请输入评论数" />
        </el-form-item>
        <el-form-item label="分享数" prop="shareCount">
          <el-input v-model="form.shareCount" placeholder="请输入分享数" />
        </el-form-item>
        <el-form-item label="收藏数" prop="collectionCount">
          <el-input v-model="form.collectionCount" placeholder="请输入收藏数" />
        </el-form-item>
        <el-form-item label="追剧数" prop="followCount">
          <el-input v-model="form.followCount" placeholder="请输入追剧数" />
        </el-form-item>
        <el-form-item label="评分" prop="ratingScore">
          <el-input v-model="form.ratingScore" placeholder="请输入评分" />
        </el-form-item>
        <el-form-item label="评分人数" prop="ratingCount">
          <el-input v-model="form.ratingCount" placeholder="请输入评分人数" />
        </el-form-item>
        <el-form-item label="状态：0下架，1上架，2审核中" prop="status">
          <el-input v-model="form.status" placeholder="请输入状态：0下架，1上架，2审核中" />
        </el-form-item>
        <el-form-item label="审核状态：0待审核，1通过，2拒绝" prop="auditStatus">
          <el-input v-model="form.auditStatus" placeholder="请输入审核状态：0待审核，1通过，2拒绝" />
        </el-form-item>
        <el-form-item label="审核拒绝原因" prop="auditReason">
          <el-input v-model="form.auditReason" placeholder="请输入审核拒绝原因" />
        </el-form-item>
        <el-form-item label="排序顺序" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入排序顺序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Dramas" lang="ts">
import { listDramas, getDramas, delDramas, addDramas, updateDramas, checkDramas, getDramasAiCheck } from '@/api/content/dramas';
import { DramasVO, DramasQuery, DramasForm, DramasAiCheckVO } from '@/api/content/dramas/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const dramasList = ref<DramasVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const loadingAiStatus = ref(true);

const queryFormRef = ref<ElFormInstance>();
const dramasFormRef = ref<ElFormInstance>();
const checkFormRef = ref<ElFormInstance>();
const checkFormDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const checkForm = reactive<{
  dramaId: string|number,
  auditStatus: number,
  auditReason: string,
  aiStatus: string
}>({
  dramaId: undefined,
  auditStatus: undefined,
  auditReason: undefined,
  aiStatus: "正在加载AI审核结果..."
})
const initFormData: DramasForm = {
  dramaId: undefined,
  title: undefined,
  subTitle: undefined,
  cover: undefined,
  poster: undefined,
  trailerUrl: undefined,
  description: undefined,
  storyLine: undefined,
  director: undefined,
  screenwriter: undefined,
  productionCompany: undefined,
  releaseDate: undefined,
  totalEpisodes: undefined,
  currentEpisodes: undefined,
  episodeDuration: undefined,
  totalDuration: undefined,
  language: undefined,
  region: undefined,
  year: undefined,
  isFinished: undefined,
  isVip: undefined,
  isNew: undefined,
  isHot: undefined,
  isRecommended: undefined,
  quality: undefined,
  ageRating: undefined,
  playCount: undefined,
  likeCount: undefined,
  commentCount: undefined,
  shareCount: undefined,
  collectionCount: undefined,
  followCount: undefined,
  ratingScore: undefined,
  ratingCount: undefined,
  status: undefined,
  auditStatus: undefined,
  auditReason: undefined,
  sortOrder: undefined,
}
const data = reactive<PageData<DramasForm, DramasQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    subTitle: undefined,
    description: undefined,
    params: {
    }
  },
  rules: {
    dramaId: [
      { required: true, message: "短剧ID不能为空", trigger: "blur" }
    ],
    title: [
      { required: true, message: "短剧标题不能为空", trigger: "blur" }
    ],
    cover: [
      { required: true, message: "封面图URL不能为空", trigger: "blur" }
    ],
    totalEpisodes: [
      { required: true, message: "总集数不能为空", trigger: "blur" }
    ],
    currentEpisodes: [
      { required: true, message: "当前集数不能为空", trigger: "blur" }
    ],
    isFinished: [
      { required: true, message: "是否完结：0连载中，1已完结不能为空", trigger: "blur" }
    ],
    isVip: [
      { required: true, message: "是否VIP专享：0否，1是不能为空", trigger: "blur" }
    ],
    isNew: [
      { required: true, message: "是否新剧：0否，1是不能为空", trigger: "blur" }
    ],
    isHot: [
      { required: true, message: "是否热播：0否，1是不能为空", trigger: "blur" }
    ],
    isRecommended: [
      { required: true, message: "是否推荐：0否，1是不能为空", trigger: "blur" }
    ],
    playCount: [
      { required: true, message: "播放次数不能为空", trigger: "blur" }
    ],
    likeCount: [
      { required: true, message: "点赞数不能为空", trigger: "blur" }
    ],
    commentCount: [
      { required: true, message: "评论数不能为空", trigger: "blur" }
    ],
    shareCount: [
      { required: true, message: "分享数不能为空", trigger: "blur" }
    ],
    collectionCount: [
      { required: true, message: "收藏数不能为空", trigger: "blur" }
    ],
    followCount: [
      { required: true, message: "追剧数不能为空", trigger: "blur" }
    ],
    ratingCount: [
      { required: true, message: "评分人数不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态：0下架，1上架，2审核中不能为空", trigger: "blur" }
    ],
    auditStatus: [
      { required: true, message: "审核状态：0待审核，1通过，2拒绝不能为空", trigger: "blur" }
    ],
    sortOrder: [
      { required: true, message: "排序顺序不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询短剧管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDramas(queryParams.value);
  dramasList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  dramasFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: DramasVO[]) => {
  ids.value = selection.map(item => item.dramaId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加短剧管理";
}
/** 审核按钮操作 */
const handleCheck = async (row?: DramasVO) => {
  reset();
  const _dramaId = row?.dramaId || ids.value[0]
  const res = await getDramasAiCheck(_dramaId);
  loadingAiStatus.value = false;
  checkForm.dramaId = _dramaId;
  checkForm.aiStatus = res.data == 0?'AI审核未通过':'AI审核通过';
  // Object.assign(form.value, res.data);
  checkFormDialog.visible = true;
  checkFormDialog.title = "短剧审核";
  
}
/** 取消审核按钮操作 */
const cancelCheckFormDialog = () => {
  checkFormDialog.visible = false;
}

const submitCheckForm = async () => {
  buttonLoading.value = true;
  await checkDramas(checkForm).finally(() =>  buttonLoading.value = false);
}

/** 修改按钮操作 */
const handleUpdate = async (row?: DramasVO) => {
  reset();
  const _dramaId = row?.dramaId || ids.value[0]
  const res = await getDramas(_dramaId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改短剧管理";
}

/** 提交按钮 */
const submitForm = () => {
  dramasFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.dramaId) {
        await updateDramas(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addDramas(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: DramasVO) => {
  const _dramaIds = row?.dramaId || ids.value;
  await proxy?.$modal.confirm('是否确认删除短剧管理编号为"' + _dramaIds + '"的数据项？').finally(() => loading.value = false);
  await delDramas(_dramaIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('content/dramas/export', {
    ...queryParams.value
  }, `dramas_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
